package cn.fl.customer.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.mid.core.framework.dto.MessageDTO;
import cn.cmm.base.framework.utils.*;
import cn.fl.customer.transform.CstBankVOTransform;
import cn.fl.framework.base.constant.WebBaseConstant;
import cn.fl.system.constant.SysInsCfgInfoConstant;
import cn.lionbridge.api.base.request.ApiCmmReqDTO;
import cn.lionbridge.api.base.request.ApiCmmReqHeadDTO;
import cn.lionbridge.api.base.result.Response;
import cn.lionbridge.api.facade.factorcheck.api.ICertApiService;
import cn.lionbridge.api.facade.factorcheck.dto.req.BankCardNumReqDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.api.ICustomerQueryApiService;
import fl.customer.facade.customer.dto.CstBscInfoDTO;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.customer.service.ICstBankService;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBankVO;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;
import cn.lb.framework.poi.excel.entity.TemplateExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelStyleType;
import fl.customer.facade.customer.condition.CstBankQueryCondition;
import fl.customer.facade.customer.constant.CustomerConstant;
import fl.customer.facade.customer.dto.CstBankDTO;
import tc.esign.facade.esign.api.ICfcaUsrApiService;
import tc.esign.facade.esign.dto.CfcaUsrDTO;
import tc.esign.facade.esign.dto.req.VerifCfcaUserReqDTO;
import tc.esign.facade.esign.dto.resp.BankCardValidateDTO;

/**
 * @Description: 客户开户银行信息表 控制层
 */
@Controller
@RequestMapping("/customer/cstbank")
public class CstBankController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstBankController.class);

	/**
	 * CstBank 服务层BEAN
	 */
	@Autowired
	private ICstBankService cstBankService;
	
	/**
	 * CstBscInfo 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	@Autowired
	private ISysDictionaryService sysDictionaryService;

	@Autowired
	private ICustomerQueryApiService customerQueryApiService;

	@Autowired
	private ICustomerApiService customerApiService;

	@Autowired
	private ICertApiService certApiService;

	/**
	 * 到管理列表页面
	 */
	@RequestMapping(value = "/toMgeListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toMgeListPage", "跳转到客户开户银行列表页面!", CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("customer/cstbank/custCstBacInfoNpBankMgtList");
		try {
			// 事业部
			List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
			view.addObject("orgListList", orgList);
			List<String> codeGrpCdList = new ArrayList<>();
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_NP_BK_CD);
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_VALID_STATUS_CD);
			codeGrpCdList.add(DictionaryConstant.CODE_SYS_YES_NO_CD);
			Map<String, List<KeyValueVO>> dicMap = this.sysDictionaryService.getMultiKvList(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
			view.addObject("searchSelectBkCdList", dicMap.get(DictionaryConstant.CODE_GRP_CST_NP_BK_CD));
			view.addObject("yNList", dicMap.get(DictionaryConstant.CODE_SYS_YES_NO_CD));
			//获取账户验证状态
			view.addObject("validStsList", dicMap.get(DictionaryConstant.CODE_GRP_VALID_STATUS_CD));
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toMgeListPage", "获取基础信息错误!" + e.getMessage());
		}
		
		return view;
	}
	
	/**
	 * 到自然人客户开户银行账号详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String cbId = request.getParameter("cbId");
		ModelAndView view = new ModelAndView("customer/cstbank/custCstBankDetail");
		view.addObject("cbId", cbId);
		BaseLogUtils.info(logger, "toDetailPage", "跳转到客户开户银行账号详情页面!", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到法人客户开户银行账号详情页面
	 */
	@RequestMapping(value = "/toCorpDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toCorpDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String cbId = request.getParameter("cbId");
		ModelAndView view = new ModelAndView("customer/cstbank/custCstCorpBankDetail");
		view.addObject("cbId", cbId);
		BaseLogUtils.info(logger, "toCorpDetailPage", "跳转到客户开户银行账号详情页面!", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		BaseLogUtils.info(logger, "toModifyPage", "跳转到客户开户银行修改页面!", CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("customer/cstbank/custCstBankModify");
		view.addObject("id", id);
		return view;
	}
	
	/**
	 * 到查看状态的列表页面
	 */
	@RequestMapping(value = "/toCustCstBacInfoNpBankDetailListPage.do", method = { RequestMethod.GET})
	public ModelAndView toCustCstBacInfoNpBankDetailListPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstbank/custCstBacInfoNpBankDetailList");
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toListPage", "跳转到查看状态的列表页面!", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到查看状态的列表页面
	 */
	@RequestMapping(value = "/toCustCstBacInfoCorpBankDetailListPage.do", method = { RequestMethod.GET})
	public ModelAndView toCustCstBacInfoCorpBankDetailListPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		ModelAndView view = new ModelAndView("customer/cstbank/custCstBacInfoCorpBankDetailList");
		view.addObject("cstId", cstId);
		BaseLogUtils.info(logger, "toListPage", "跳转到查看状态的列表页面!", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到新增修改客户开户银行账号信息
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		String cbId = request.getParameter("cbId");
		ModelAndView view = new ModelAndView("customer/cstbank/custCstBankAdd");
		try {
			setDataForToAddPage(view);
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toAddPage", "获取基础信息错误!" + e.getMessage());
		}
		//获取客户
		CstBscInfoVO cstBscInfoVO = null;
		try {
			cstBscInfoVO = this.cstBscInfoService.selectById(Long.valueOf(cstId));
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toAddPage", "获取客户基础信息错误!" + e.getMessage());
		}
		if(null != cstBscInfoVO){
			view.addObject("certNo", cstBscInfoVO.getCertNo());
			view.addObject("certTypCd", cstBscInfoVO.getCertTypCd());
		}else{
			view.addObject("certNo", "");
			view.addObject("certTypCd", "");
		}
		
		view.addObject("cstId", cstId);
		view.addObject("cbId", cbId);//修改时使用的关联关系ID
		BaseLogUtils.info(logger, "toAddPage", "跳转到客户开户银行新增/修改页面!", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到新增修改客户开户银行账号信息
	 */
	@RequestMapping(value = "/toCorpAddPage.do", method = { RequestMethod.GET })
	public ModelAndView toCorpAddPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		String cbId = request.getParameter("cbId");
		ModelAndView view = new ModelAndView("customer/cstbank/custCstCorpBankAdd");
		try {
			setDataForToAddPage(view);
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "toCorpAddPage", "获取基础信息错误!" + e.getMessage());
		}catch (Exception e) {
			BaseLogUtils.error(logger, "toCorpAddPage", "获取基础信息错误!" + e.getMessage());
		}
		view.addObject("cstId", cstId);
		view.addObject("cbId", cbId);//修改时使用的关联关系ID
		BaseLogUtils.info(logger, "toCorpAddPage", "跳转到客户开户银行新增/修改页面!", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 新增修改页面返回页面数据
	 * @param view
	 */
	private void setDataForToAddPage(ModelAndView view) {
		String sysCd = CurrentThreadContext.getFlServiceSysCd();
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		List<String> codeGrpCdList = new ArrayList<>();
		codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_NP_BK_CD);
		codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_NP_ACC_TYP_CD);
		Map<String, List<KeyValueVO>> map = this.sysDictionaryService.getMultiKvList(sysCd, orgCd, codeGrpCdList);
		if(CollectionUtils.isMapEmpty(map)){
			map = new HashMap<>();
		}
		//证件类型
		List<KeyValueVO> certTypCdList = this.cstBscInfoService.searchCertTypCdList(CustomerConstant.CST_TYP_CD_NP);
		view.addObject("searchSelectCertTypCdList", certTypCdList);
		//开户银行
		List<KeyValueVO> bkCdList =  map.get(DictionaryConstant.CODE_GRP_CST_NP_BK_CD);
		if(CollectionUtils.isEmpty(bkCdList)){
			bkCdList = new ArrayList<>();
		}
		view.addObject("searchSelectBkCdList", bkCdList);
		//账户类型
		List<KeyValueVO> accTypCdList = map.get(DictionaryConstant.CODE_GRP_CST_NP_ACC_TYP_CD);
		if(CollectionUtils.isEmpty(accTypCdList)){
			accTypCdList = new ArrayList<>();
		}
		view.addObject("searchSelectAccTypCdList", accTypCdList);
		//是否代扣卡
		/*List<KeyValueVO> yesOrNoList = this.cstBankService.searchYesOrNoList();
		view.addObject("searchSelectYesOrNoList", yesOrNoList);*/
		//是否缺省代扣卡
		/*List<KeyValueVO> defYesOrNoList = this.cstBankService.searchYesOrNoList();
		view.addObject("searchSelectDefYesOrNoList", defYesOrNoList);*/
	}

	/**
	 * 初始化列表-提供给客户管理中代扣卡页面使用
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstId = request.getParameter("cstId");
		String isEncrypt=request.getParameter("isEncrypt");

		if(StringUtils.isEmpty(cstId)){
			ListPageVO<CstBankVO> listPage = new ListPageVO<CstBankVO>(new ArrayList<CstBankVO>(), 0);
			BaseLogUtils.info(logger, "initList", "参数ID不存在,直接返回空集合!", CurrentThreadContext.getCurrentUserName());
			return listPage;
		}
		String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstBankQueryCondition qc = new CstBankQueryCondition();
		List<Long> cstIdList = new ArrayList<>();
		cstIdList.add(Long.valueOf(cstId));
		qc.setCstIdList(cstIdList);
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		//qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		page.setCondition(qc);
		//page.setEveryPage(Integer.MAX_VALUE);//最大数据量
		Pager pager = this.cstBankService.searchListPage(page);
		List<CstBankVO> list = (List<CstBankVO>) pager.getResultList();
		if(CollectionUtils.isNotEmpty(list) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)){
			for (CstBankVO vo:list){
				vo.setAccNo(EncryptUtil.cardNoEncrypt(vo.getAccNo()));
				vo.setCertNo(EncryptUtil.certNoEncrypt(vo.getCertNo()));
			}
		}
		ListPageVO<CstBankVO> listPage = new ListPageVO<CstBankVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "初始化数据page参数!" + com.alibaba.fastjson.JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 初始化列表-提供给客户管理中验证代扣卡页面使用
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initMgeList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initMgeList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstNm = request.getParameter("cstNm");
		String bkCd = request.getParameter("bkCd");
		String accOrgNm = request.getParameter("accOrgNm");
		String accNm = request.getParameter("accNm");
		String accNo = request.getParameter("accNo");
		String certNo = request.getParameter("certNo");
		String buOrgCd = request.getParameter("buOrgCd");
		String audStsCd = request.getParameter("audStsCd");//验证状态
		String isValid = request.getParameter("isValid");//是否有效
		String startDt = request.getParameter("startDt");//开始时间
		String endDt = request.getParameter("endDt");//结束时间
		
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstBankQueryCondition qc = new CstBankQueryCondition();
		page.setCondition(qc);
		if(StringUtils.isNotEmpty(cstNm)){
			qc.setCstNm(cstNm);
		}
		
		if(StringUtils.isNotEmpty(bkCd)){
			qc.setBkCd(bkCd);
		}
		
		if(StringUtils.isNotEmpty(accOrgNm)){
			qc.setAccOrgNm(accOrgNm);
		}
		
		if(StringUtils.isNotEmpty(accNm)){
			List<String> accNmList = new ArrayList<>();
			accNmList.add(accNm);
			qc.setAccNmList(accNmList);
		}
		
		if(StringUtils.isNotEmpty(accNo)){
			List<String> accNoList = new ArrayList<>();
			accNoList.add(accNo);
			qc.setAccNoList(accNoList);
		}
		
		if(StringUtils.isNotEmpty(certNo)){
			qc.setCertNo(certNo);
		}
		
		if(StringUtils.isNotEmpty(buOrgCd)){
			qc.setBuOrgCd(buOrgCd);
		}
		
		if(StringUtils.isNotEmpty(audStsCd)){
			qc.setAudStsCd(audStsCd);
		}
		
		if(StringUtils.isNotEmpty(isValid)){
			qc.setIsValid(Integer.valueOf(isValid));
		}
		
		if(StringUtils.isNotEmpty(startDt)){
			try {
				DateUtils.formatStringToDate(startDt, DateUtils.YYYY_MM_DD);
				qc.setStartDtStr(startDt);
			} catch (Exception e) {
				BaseLogUtils.info(logger, "initMgeList", "开始时间解析错误!");
			}
		}
		
		if(StringUtils.isNotEmpty(endDt)){
			try {
				DateUtils.formatStringToDate(endDt, DateUtils.YYYY_MM_DD);
				qc.setEndDtStr(endDt);
			} catch (Exception e) {
				BaseLogUtils.info(logger, "initMgeList", "结束时间解析错误!");
			}
		}
		
		qc.setIsDeduct(BaseConstant.IS_YESNO_YES);//只是代扣卡的数据
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		Pager pager = this.cstBankService.searchListPage(page);
		List<CstBankVO> list = (List<CstBankVO>) pager.getResultList();
		ListPageVO<CstBankVO> listPage = new ListPageVO<CstBankVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initMgeList", "初始化数据page参数!" + com.alibaba.fastjson.JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeById", "参数ID不存在", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			List<Long> idList = new ArrayList<>();
			idList.add(Long.valueOf(id));
			this.cstBankService.removeByIds(idList);
			BaseLogUtils.info(logger, "removeById", "删除数据成功！ID:" + id, CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败！ID:" + id + "-ERROR: " + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败！ID:" + id + "-ERROR: " + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String isEncrypt = request.getParameter("isEncrypt");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "查询主键不存在", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();

			CstBankVO vo = this.cstBankService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据不存在！ID:"+id, CurrentThreadContext.getCurrentUserName());
			}else {
				BaseLogUtils.info(logger, "getById", "获取数据成功！ID:" + id, CurrentThreadContext.getCurrentUserName());
				if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
					vo.setCertNo(EncryptUtil.certNoEncrypt(vo.getCertNo()));
					vo.setAccNo(EncryptUtil.cardNoEncrypt(vo.getAccNo()));
				}
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取数据失败！ID:"+id + "-ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getById", "获取数据失败！ID:"+id + "-ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CstBankVO entity = null;
		try {
			entity = this.getRequestParams(request, CustomerConstant.CST_TYP_CD_NP);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setAudStsCd(CustomerConstant.CODE_BANK_NOT_VALID_CD);//默认未验证
			entity.setIsDeduct(BaseConstant.IS_YESNO_NO);//默认不是划扣卡
			//entity.setIsDefDeduct(BaseConstant.IS_YESNO_NO);//默认非默认划扣卡
			entity.setRegWayCd(PropertiesCacheUtils.getProperty(fl.constant.facade.framework.constant.DictionaryConstant.CODE_CST_BANK_REG_WAY_CD_WEB));
			Long id = this.cstBankService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增成功！ID:"+id + "-DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增失败！" + "-DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增失败！" + "-DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	/**
	 * 新增法人账户
	 */
	@RequestMapping(value = "/addForCorp.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addForCorp(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CstBankVO entity = null;
		try {
			entity = this.getRequestParams(request, CustomerConstant.CST_TYP_CD_CORP);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setAudStsCd(CustomerConstant.CODE_BANK_NOT_VALID_CD);//默认未验证
			entity.setIsDeduct(BaseConstant.IS_YESNO_NO);//默认不是划扣卡
			//entity.setIsDefDeduct(BaseConstant.IS_YESNO_NO);//默认非默认划扣卡
			entity.setRegWayCd(PropertiesCacheUtils.getProperty(fl.constant.facade.framework.constant.DictionaryConstant.CODE_CST_BANK_REG_WAY_CD_WEB));
			Long id = this.cstBankService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addForCorp", "新增成功！ID:"+id + "-DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "addForCorp", "新增失败！" + "-DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addForCorp", "新增失败！" + "-DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改客户开户银行信息
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改参数中主键不存在！" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CstBankVO entity = null;
		try {
			entity = this.getRequestParams(request, CustomerConstant.CST_TYP_CD_NP);
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.cstBankService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modify", "修改失败！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) , CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "modify", "修改成功！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) , CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage() , CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "modify", "修改失败！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage() , CurrentThreadContext.getCurrentUserName());
		}
		return result;
		
	}
	
	/**
	 * 修改客户开户银行信息
	 */
	@RequestMapping(value = "/modifyForCorp.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyForCorp(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyForCorp", "修改参数中主键不存在！" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CstBankVO entity = null;
		try {
			entity = this.getRequestParams(request, CustomerConstant.CST_TYP_CD_CORP);
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.cstBankService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyForCorp", "修改失败！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) , CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "modifyForCorp", "修改成功！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) , CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyForCorp", "修改失败！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage() , CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "modifyForCorp", "修改失败！DATA:" + com.alibaba.fastjson.JSONObject.toJSONString(entity) + "-ERROR:" + ex.getMessage() , CurrentThreadContext.getCurrentUserName());
		}
		return result;
		
	}
	
	
	/**
	 * 修改验证状态
	 */
	@RequestMapping(value = "/modifyAudStsCd.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyValidSts(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "验证成功!");
		String id = request.getParameter("id");
		String validSts = request.getParameter("validSts");
		String _bkCd = request.getParameter("bkCd");
		String accRem = request.getParameter("accRem");
		
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyValidSts", "修改参数中主键不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		if(StringUtils.isEmpty(_bkCd)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("开户银行类型不能为空!");
			BaseLogUtils.info(logger, "modifyValidSts", "开户银行类型不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		//如果是邮储代扣则不能修改验证状态
		/*if(_bkCd.equals(DictionaryConstant.CODE_GRP_CST_NP_BK_CD_POST)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("没有权限验证中国邮政储蓄代扣卡!");
			BaseLogUtils.info(logger, "modifyValidSts", "没有权限验证中国邮政储蓄代扣卡!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}*/
		
		if(StringUtils.isEmpty(validSts)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("验证状态不能为空!");
			BaseLogUtils.info(logger, "modifyValidSts", "验证状态不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		StringBuffer params = new StringBuffer();
		params.append("id:");
		params.append(id);
		params.append(",validSts");
		params.append(validSts);
		try {
			Boolean b = this.cstBankService.modifyAudStsCd(Long.valueOf(id), validSts, accRem);
			if(false == b){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("验证失败!");
				BaseLogUtils.info(logger, "modifyValidSts", "验证状态不能为空!" , CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "modifyValidSts", "验证成功！ID:"+id + "-DATA:"+params.toString(), CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyValidSts", "验证失败！" + "-DATA:"+params.toString() + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifyValidSts", "验证失败！" + "-DATA:"+params.toString() + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	
	
	/**
	 * 修改是否有效状态
	 */
	@RequestMapping(value = "/modifyIsValid.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyIsValid(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		String id = request.getParameter("id");
		String isValid = request.getParameter("isValid");
		
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyIsValid", "主键不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		if(StringUtils.isEmpty(isValid)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("请选择是否有效状态!");
			BaseLogUtils.info(logger, "modifyIsValid", "请选择是否有效状态!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			Boolean b = this.cstBankService.modifyIsValid(Long.valueOf(id), isValid);
			if(false == b){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("操作失败!");
				BaseLogUtils.info(logger, "modifyIsValid", "验证状态不能为空!" , CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "modifyIsValid", "验证成功！ID:"+id , CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyIsValid", "验证失败！" + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifyIsValid", "验证失败！" + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	/**
	 * 下载
	 */
	@SuppressWarnings("resource")
	@RequestMapping(value = "/downList.do", method = { RequestMethod.GET })
	public void downList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String cstNm = request.getParameter("cstNm");
		String bkCd = request.getParameter("bkCd");
		String accOrgNm = request.getParameter("accOrgNm");
		String accNm = request.getParameter("accNm");
		String accNo = request.getParameter("accNo");
		String certNo = request.getParameter("certNo");
		String buOrgCd = request.getParameter("buOrgCd");
		String audStsCd = request.getParameter("audStsCd");//验证状态
		String isValid = request.getParameter("isValid");//是否有效
		String startDt = request.getParameter("startDt");//开始时间
		String endDt = request.getParameter("endDt");//结束时间
		
		CstBankQueryCondition qc = new CstBankQueryCondition();
		if(StringUtils.isNotEmpty(cstNm)){
			qc.setCstNm(cstNm);
		}
		
		if(StringUtils.isNotEmpty(bkCd)){
			qc.setBkCd(bkCd);
		}
		
		if(StringUtils.isNotEmpty(accOrgNm)){
			qc.setAccOrgNm(accOrgNm);
		}
		
		if(StringUtils.isNotEmpty(accNm)){
			List<String> accNmList = new ArrayList<>();
			accNmList.add(accNm);
			qc.setAccNmList(accNmList);
		}
		
		if(StringUtils.isNotEmpty(accNo)){
			List<String> accNoList = new ArrayList<>();
			accNoList.add(accNo);
			qc.setAccNoList(accNoList);
		}
		
		if(StringUtils.isNotEmpty(certNo)){
			qc.setCertNo(certNo);
		}
		
		if(StringUtils.isNotEmpty(buOrgCd)){
			qc.setBuOrgCd(buOrgCd);
		}
		
		if(StringUtils.isNotEmpty(audStsCd)){
			qc.setAudStsCd(audStsCd);
		}
		
		if(StringUtils.isNotEmpty(isValid)){
			qc.setIsValid(Integer.valueOf(isValid));
		}
		
		if(StringUtils.isNotEmpty(startDt)){
			try {
				DateUtils.formatStringToDate(startDt, DateUtils.YYYY_MM_DD);
				qc.setStartDtStr(startDt);
			} catch (Exception e) {
				BaseLogUtils.info(logger, "initMgeList", "开始时间解析错误!");
			}
		}
		
		if(StringUtils.isNotEmpty(endDt)){
			try {
				DateUtils.formatStringToDate(endDt, DateUtils.YYYY_MM_DD);
				qc.setEndDtStr(endDt);
			} catch (Exception e) {
				BaseLogUtils.info(logger, "initMgeList", "结束时间解析错误!");
			}
		}
		
		qc.setIsDeduct(BaseConstant.IS_YESNO_YES);
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		//qc.setAudStsCd(CustomerConstant.CODE_GRP_VALID_STATUS_CD_1);
		
		List<CstBankVO> list = this.cstBankService.searchList(qc);
		List<CstBankVO> importList = new ArrayList<>();
		if (CollectionUtils.isEmpty(list)) {
			list = new ArrayList<>();
		}else{
			//过滤掉邮储的数据
			for (CstBankVO cstBankVO : list) {
				/*if(cstBankVO.getBkCd().equals(DictionaryConstant.CODE_GRP_CST_NP_BK_CD_POST)){
					continue;
				}*/
				importList.add(cstBankVO);
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("bkList", importList);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		String filename = "银行帐号(代扣卡)" + (new Date()).getTime();
		response.setCharacterEncoding("utf-8");
		OutputStream os = null;
		try {
			filename = new String(filename.getBytes("GBK"), "ISO8859-1");
			response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");// 设定输出文件头
			response.setContentType("application/x-msdownload");// 定义输出类型
			baos = downBankForMgeXls(map);
			os = response.getOutputStream();
			baos.writeTo(os);
			baos.flush();
			os.flush();
		} catch (UnsupportedEncodingException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		} finally {
			// 关闭流
			if (os != null) {
				try {
					os.close();
					os = null;
				} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
				}
			}
			if (baos != null) {
				try {
					baos.close();
					baos = null;
				} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
				}
			}
		}
	}
	
	
	/**
     * 导出银行帐号For财务
     * @param map
     * @return
     */
	public ByteArrayOutputStream downBankForMgeXls(Map<String, Object> map) {
        ByteArrayOutputStream baos = null;
        //List<CstBankVO> list = (List<CstBankVO>) map.get("bkList");
        //map.put("bkList",list);
        TemplateExportParams params = new TemplateExportParams(CstBankController.class.getClassLoader().getResource("/template/customer/customerBankAccount.xls").getFile(), false, "银行帐号");
        params.setHeadingRows(0);
        params.setHeadingStartRow(1);
        params.setStyle(ExcelStyleType.BORDER.getClazz());
        params.setColForEach(true);//注：包含遍历list
        params.setDataSheetNum(2);
        try {
            Workbook book = ExcelExportUtil.exportExcel(params, map);
            baos = new ByteArrayOutputStream();
            book.write(baos);
        } catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
        }finally {
			if(null != baos){
				try {
					baos.close();
				} catch (IOException e) {
				}
			}
		}
        return baos;
    }
	
	/**
	 * 上传数据
	 */
	@RequestMapping(value = "/importBank.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO importBank(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "导入成功");
        String filePath=request.getParameter("filePath");//文件路径
        //filePath = "C://uploadfile/11000/customer/temp/20161226134710/ae99dd4997cd40fa84942e1d289f5887.xls";
        try {
        	String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);
        	String realPath = rootPath + filePath;
        	BaseLogUtils.info(logger, "importBank", "上传文件路径："+realPath);
        	List<CstBankVO> list= importXls(realPath);
            if(CollectionUtils.isNotEmpty(list)){
                this.cstBankService.importCstBank(list);
                BaseLogUtils.info(logger, "importBank", "导入成功.DATA:"+filePath, CurrentThreadContext.getCurrentUserName());
            }else{
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("未获取到要处理的数据!");
                BaseLogUtils.info(logger, "importBank", "导入失败.导入数据为空", CurrentThreadContext.getCurrentUserName());
            }
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyValidSts", "验证失败！" + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifyValidSts", "验证失败！" + "-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
        
        return result;
    }
	
	
	/**
	 * 修改是否代扣卡
	 */
	@RequestMapping(value = "/modifyIsDeduct.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyIsDeduct(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		String id = request.getParameter("id");
		String isDeduct = request.getParameter("isDeduct");
		String isDefDeduct = request.getParameter("isDefDeduct");
		String isDecuctOld = request.getParameter("isDecuctOld");
		
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyIsDeduct", "主键不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		if(StringUtils.isEmpty(isDeduct)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("是否代扣卡不能为空!");
			BaseLogUtils.info(logger, "modifyIsDeduct", "是否代扣卡不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		if(StringUtils.isEmpty(isDecuctOld)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("原代扣卡值不能为空!");
			BaseLogUtils.info(logger, "modifyIsDeduct", "原代扣卡值不能为空!" , CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		if(StringUtils.isEmpty(isDefDeduct)){
			isDefDeduct = isDeduct;
		}
		
		try {
			String audStsCd = null;//CustomerConstant.CODE_BANK_NOT_VALID_CD;
			Integer isValid = null;//BaseConstant.IS_YESNO_NO;
			Boolean b = this.cstBankService.modifyIsDeduct(Long.valueOf(id), Integer.valueOf(isDeduct), 
					Integer.valueOf(isDefDeduct), audStsCd, isValid, CurrentThreadContext.getCurrentUserId());
			if(false == b){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
				BaseLogUtils.info(logger, "modifyIsDeduct", "验证状态不能为空!" , CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "modifyIsDeduct", "验证成功！ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyIsDeduct", "修改失败！-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifyIsDeduct", "修改失败！-ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	//*************************私有属性新增修改共用**********************//
	
	/**
     * 导入帐号
     * @param filePath 源文件路径
     * @return
     */
    private List<CstBankVO> importXls(String filePath) throws BaseException{
        ImportParams params = new ImportParams();
        params.setTitleRows(0);//标题占用行数
        params.setHeadRows(1);//表头占用行数
        params.setNeedSave(false);//是否保存文件

        List<CstBankVO> list = null;
        File file=new File(filePath);
        if(file.exists()){
            list = ExcelImportUtil.importExcel(file, CstBankVO.class, params);
            if(CollectionUtils.isNotEmpty(list)){
            	//获取验证状态
            	Map<String, String> compareMap = new HashMap<>();
            	for (Map.Entry<String, String> getMap : DictionaryConstant.getCstBankAudStsCdMap.entrySet()) {
            		compareMap.put(getMap.getValue(), getMap.getKey());
				}
            	
            	BaseLogUtils.info(logger, "importXls", "导入客户帐号="+filePath+",记录条数="+list.size());
                StringBuffer errMsg = new StringBuffer();
                boolean pass = true;
                Date currentDate = new Date();
                for(CstBankVO vo:list){
                    if(StringUtils.isBlank(vo.getCstNm())){
                        errMsg.append("所属客户不能为空; ");
                        pass = false;
                    }
                    
                    if(StringUtils.isBlank(vo.getAccNm())){
                        errMsg.append("开户名称不能为空; ");
                        pass = false;
                    }
                    
                    if(StringUtils.isBlank(vo.getAccNo())){
                        errMsg.append("银行帐号不能为空; ");
                        pass = false;
                    }
                    
                    String audStsCdNm = vo.getAudStsCdNm();
                    if(StringUtils.isEmpty(audStsCdNm)){
                    	 errMsg.append("验证状态不能为空; ");
                    	 pass = false;
                    }else{
                    	//如果三个验证状态不存在则提示
                    	if(!DictionaryConstant.getCstBankAudStsCdMap.containsValue(audStsCdNm)){
                    		 errMsg.append("验证状态只能选择下拉列表值; ");
                        	 pass = false;
                    	}
                    	vo.setAudStsCd(compareMap.get(audStsCdNm));
                    }
                    
                    String isValidNm = vo.getIsValidNm();
                    if(StringUtils.isEmpty(isValidNm)){
                    	if(!BaseConstant.IS_YESNO_NO_NE.equals(isValidNm)
                    			&& !BaseConstant.IS_YESNO_YES_NM.equals(isValidNm)){
                    		errMsg.append("是否有效只能选择下拉列表值; ");
                    	}
                    	if(BaseConstant.IS_YESNO_NO_NE.equals(isValidNm)){
                    		vo.setIsValid(BaseConstant.IS_YESNO_NO);
                    	}else if(BaseConstant.IS_YESNO_YES_NM.equals(isValidNm)){
                    		vo.setIsValid(BaseConstant.IS_YESNO_YES);
                    	}
                    	
                    }
                    
                    if(StringUtils.isEmpty(vo.getAccRem())){
                    	//errMsg.append("验证备注为空; ");
                    }
                    
                    if(StringUtils.isEmpty(vo.getCstId())){
                    	errMsg.append("cstId不能为空; ");
                    	 pass = false;
                    }
                    
                    if(StringUtils.isEmpty(vo.getBkId())){
                    	errMsg.append("bkId不能为空; ");
                    	 pass = false;
                    }else{
                    	vo.setId(vo.getBkId());
                    }
                    //错误提示
                    if(pass == false){
                    	throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_602, "数据解析错误:" + errMsg.toString());
                    }
                    vo.setMdfTm(currentDate);
                    vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                }
            }
        }
        return list;
    }

	
	
	/**
	 * 获取请求参数
	 * @param request
	 * @param cstTypCd 然人  或者 法人
	 * @return
	 * @throws BaseException
	 */
	private CstBankVO getRequestParams(HttpServletRequest request, String cstTypCd) throws BaseException{
		String cstId = request.getParameter("cstId");//客户id
		String bkCd = request.getParameter("bkCd");//银行代码
		String accNm = request.getParameter("accNm");//账户名称
		String accNo = request.getParameter("accNo");//银行账号
		String accTypCd = request.getParameter("accTypCd");//账户类型
		String accOrgNm = request.getParameter("accOrgNm");//开户机构
		String certTypCd = request.getParameter("certTypCd");//证件类型
		String certNo = request.getParameter("certNo");//证件号码
		String cardTel = request.getParameter("cardTel");//银行预留手机号
		//String isDeduct = request.getParameter("isDeduct");//是否划扣卡
		//String isDefDeduct = request.getParameter("isDefDeduct");//是否缺省划扣卡	
		String bkNo = request.getParameter("bkNo");
		
		//验证必填项
		if (StringUtils.isBlank(cstId)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请确定客户是否存在");
		}
		if (StringUtils.isBlank(bkCd)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择银行代码!");
		}
		if (StringUtils.isBlank(accNm)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写开户名称!");
		}
		if (StringUtils.isBlank(accOrgNm)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写开户机构!");
		}
		if (StringUtils.isBlank(accNo)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写银行账号!");
		}
		if (StringUtils.isBlank(accTypCd)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择账户类型!");
		}
		if (StringUtils.isBlank(cardTel)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写银行预留手机号!");
		}else{
		    if (StringUtils.isNotEmpty(cardTel) && !StringUtils.checkMobileNumber(cardTel)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请输入正确的银行预留手机号!");
            }
        }
		
//		if (StringUtils.isBlank(isDeduct)) {
//			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择是否代扣卡!");
//		}
		if(StringUtils.isEmpty(bkNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "开户行行号不能为空!");
		}
		
		//验证银行账号只能为数字
		if (!StringUtils.isNumeric(accNo)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "银行账号只能为数字");
		}
		
		if(CustomerConstant.CST_TYP_CD_CORP.equals(cstTypCd)){//法人
			
		}else if(CustomerConstant.CST_TYP_CD_NP.equals(cstTypCd)){//自然人
			if (StringUtils.isBlank(certTypCd)) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择证件类型!");
			}
			if (StringUtils.isBlank(certNo)) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写证件号!");
			}

			ApiCmmReqDTO<BankCardNumReqDTO> apiCmmReqDTO = new ApiCmmReqDTO<BankCardNumReqDTO>();
			ApiCmmReqHeadDTO apiCmmReqHeadDTO = new ApiCmmReqHeadDTO();
			apiCmmReqHeadDTO.setBid("f5763cea84b943d48eb22f3b8a830be3");
			apiCmmReqHeadDTO.setPid("GHSKKL8IEADS1");
			apiCmmReqDTO.setHead(apiCmmReqHeadDTO);
			BankCardNumReqDTO bankCardNumReqDTO = new BankCardNumReqDTO();
			bankCardNumReqDTO.setUserName(accNm);
			bankCardNumReqDTO.setCertNoType(certTypCd);
			bankCardNumReqDTO.setCertNo(certNo);
			bankCardNumReqDTO.setAccountNo(accNo);
			bankCardNumReqDTO.setMobilePhone(cardTel);
			apiCmmReqDTO.setBody(bankCardNumReqDTO);
			BaseLogUtils.newLogger("调用四要素校验接口Start:request={}", JSONObject.toJSONString(apiCmmReqDTO)).info();
			Response response = this.certApiService.bankCardFourElementsVerify(apiCmmReqDTO);
			BaseLogUtils.newLogger("调用四要素校验接口End:messageDTO={}", JSONObject.toJSONString(response)).info();
			if (null == response || !response.isSuccess()) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "四要素校验失败!");
			}
		}

		CstBankVO entity = new CstBankVO();
		entity.setCstId(Long.valueOf(cstId));
		entity.setBkCd(bkCd);
		entity.setAccNm(accNm);
		entity.setAccNo(accNo);
		entity.setAccTypCd(accTypCd);
		entity.setAccOrgNm(accOrgNm);
		entity.setCertTypCd(certTypCd);
		entity.setCertNo(certNo);
		entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		entity.setBkNo(bkNo);
		entity.setCardTel(cardTel);// 银行预留手机号
		entity.setIsValid(BaseConstant.IS_YESNO_NO);//默认无效
		/*if(StringUtils.isNotBlank(isDeduct)){
			entity.setIsDeduct(Integer.valueOf(isDeduct));
		}*/
		/*if(StringUtils.isNotBlank(isDefDeduct)){
			entity.setIsDefDeduct(Integer.valueOf(isDefDeduct));
		}*/
		return entity;
	}

	/**
	 * 修改浙商bkCd
	 * @param request
	 * @throws BaseException
	 */
	@RequestMapping(value = "/modifyCstBkCd.do", method = { RequestMethod.GET})
	@ResponseBody
	public DataResultVO modifyCstBkCd(HttpServletRequest request) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改浙商bkCd执行中...");
		BaseLogUtils.info(logger, "modifyCstBkCd", "修改浙商bkCd====开始", CurrentThreadContext.getCurrentUserName());
		this.cstBankService.modifyCstBkCd();
		BaseLogUtils.info(logger, "modifyCstBkCd", "修改浙商bkCd====结束", CurrentThreadContext.getCurrentUserName());
		return result;
	}

	/**
	 * 初始化列表-客户银行卡列表（来自在线准入的银行卡信息）
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initBanks.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initBanks(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initBanks", "客户银行卡列表（来自在线准入的银行卡信息）.开始时间：" + startTm + "-参数：" + this.getRequestParameter(request));
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "查询客户银行卡列表成功");
		String cstId = request.getParameter("cstId");//客户Id
		String accNo = request.getParameter("accNo");//账号
		if(StringUtils.isEmpty(cstId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("客户id为空");
			BaseLogUtils.info(logger, "initBanks", "客户id为空", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CstBscInfoDTO cstBscInfoDTO  = this.customerQueryApiService.getCstBscInfoById(Long.valueOf(cstId));
		BaseLogUtils.info(logger, "initBanks", "客户银行卡列表.客户查询返回结果==>" + JSON.toJSONString(cstBscInfoDTO));
		if(cstBscInfoDTO == null){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("客户为空");
			BaseLogUtils.info(logger, "initBanks", "客户为空", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		ListPageVO<CstBankVO> listPage = null;
		try {
			CstBankQueryCondition cstBankQueryCondition = new CstBankQueryCondition();
			//cstBankQueryCondition.setIsValid(BaseConstant.IS_YESNO_YES);
			cstBankQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
			cstBankQueryCondition.setCstIds(cstId);
			//增加证件号校验确保是本人卡
			cstBankQueryCondition.setCertNo(cstBscInfoDTO.getCertNo());
			cstBankQueryCondition.setRegWayCds("\'11003\',\'11005\'");
			//cstBankQueryCondition.setRegWayCd(WebBaseConstant.DS_CD_ONLION);
			cstBankQueryCondition.setAudStsCd(BaseConstant.IS_YESNO_YES_STR);//审核通过
			if(StringUtils.isNotEmpty(accNo)) {
				cstBankQueryCondition.setAccNo(accNo);
			}
			BaseLogUtils.info(logger, "initBanks", "客户银行卡列表（来自在线准入的银行卡信息）.传入参数==>" + JSON.toJSONString(cstBankQueryCondition));
			List<CstBankDTO> cstBankDTOList = this.customerApiService.selectCstBankDetList(cstBankQueryCondition);
			BaseLogUtils.info(logger, "initBanks", "客户银行卡列表（来自在线准入的银行卡信息）.查询结果==>" + JSON.toJSONString(cstBankDTOList));
			List<CstBankVO> CstBankVOList = CstBankVOTransform.toVOList(cstBankDTOList);
			listPage = new ListPageVO<CstBankVO>(CstBankVOList, CstBankVOList.size());
			result.setData(CstBankVOList);
		}catch (BaseException e1) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(e1.getMessage());
			BaseLogUtils.info(logger, "initBanks", e1.getMessage());
		} catch (Exception e2) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("银行卡列表获取失败!");
			BaseLogUtils.info(logger, "initBanks", "客户银行卡列表（来自在线准入的银行卡信息）.获取失败" + e2);
		}
		BaseLogUtils.info(logger, "initBanks", "客户银行卡列表（来自在线准入的银行卡信息）.返回结果：" + JSON.toJSONString(result));
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initBanks", "客户银行卡列表（来自在线准入的银行卡信息）.耗时：" + (endTm - startTm));
		return listPage;
	}
}

